package edu.jimei.projecttachy.controller;

import edu.jimei.projecttachy.entity.DataSource;
import edu.jimei.projecttachy.entity.ReportTask;
import edu.jimei.projecttachy.entity.User;
import edu.jimei.projecttachy.repository.DataSourceRepository;
import edu.jimei.projecttachy.repository.UserRepository;
import edu.jimei.projecttachy.service.ReportTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;

record ReportTaskDto(Long id, String name, String dataSource, String status, String content, Instant created, String duration) {
    public static ReportTaskDto fromEntity(ReportTask task) {
        return new ReportTaskDto(
                task.getId(),
                task.getName(),
                task.getDataSource() != null ? task.getDataSource().getName() : null,
                task.getStatus(),
                task.getContent(),
                task.getCreated(),
                task.getDuration()
        );
    }
}

record CreateReportRequestDto(String name, Long dataSourceId) {}

@RestController
@RequestMapping("/api/reports")
public class ReportController {
    @Autowired
    private ReportTaskService reportTaskService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private DataSourceRepository dataSourceRepository;

    @GetMapping
    public List<ReportTaskDto> getAll() {
        return reportTaskService.findAll().stream()
                .map(ReportTaskDto::fromEntity)
                .collect(Collectors.toList());
    }

    @GetMapping("/{id}")
    public ReportTaskDto getById(@PathVariable Long id) {
        ReportTask task = reportTaskService.findById(id).orElseThrow();
        return ReportTaskDto.fromEntity(task);
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public ReportTaskDto create(@RequestBody CreateReportRequestDto request) {
        if (request.dataSourceId() == null) {
            throw new IllegalArgumentException("Data source ID must be provided to create a report.");
        }
        
        DataSource dataSource = dataSourceRepository.findById(request.dataSourceId())
                .orElseThrow(() -> new RuntimeException("DataSource not found: " + request.dataSourceId()));
        
        ReportTask task = new ReportTask();
        task.setName(request.name());
        task.setDataSource(dataSource);
        task.setStatus("Pending");

        String userEmail = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userRepository.findByEmail(userEmail)
                .orElseThrow(() -> new RuntimeException("User not found: " + userEmail));
        task.setUser(user);

        ReportTask savedTask = reportTaskService.save(task);
        return ReportTaskDto.fromEntity(savedTask);
    }

    @PutMapping("/{id}")
    public ReportTaskDto update(@PathVariable Long id, @RequestBody ReportTask task) {
        task.setId(id);
        ReportTask updatedTask = reportTaskService.save(task);
        return ReportTaskDto.fromEntity(updatedTask);
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable Long id) {
        reportTaskService.findById(id).ifPresent(task -> reportTaskService.save(task));
    }

    @PostMapping("/{id}/refresh")
    @ResponseStatus(HttpStatus.ACCEPTED)
    public void refresh(@PathVariable Long id) {
        reportTaskService.refreshReportTask(id);
    }
} 